package com.example.util;

import com.baidu.aip.face.AipFace;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by youkun on 2018/1/22.
 * 人脸识别
 */
public class FaceUtile {
    //设置APPID/AK/SK
    public static final String APP_ID = "11112009";
    public static final String API_KEY = "ti1I4afqleE5QcwyGiDI8Rrg";
    public static final String SECRET_KEY = "jv2wqwNjGqnOnIEz304S3Sqtry1Pq7y2";
    private  static AipFace client = null;

    static {
        client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
        // 可选：建立连接的超时时间（单位：毫秒）
        client.setConnectionTimeoutInMillis(2000);
        //通过打开的连接传输数据的超时时间（单位：毫秒）
        client.setSocketTimeoutInMillis(60000);
    }

    public static void main(String[] args) {
        String image = "/Users/youkun/Pictures/bb.jpg";
        try {
            //System.out.print( FaceDetect(image));
            System.out.print(FaceMatch(image,image));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 人脸检测
     * @param imagePath
     * @return
     */
    public static JSONObject FaceDetect(String imagePath) throws Exception{
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("face_fields","age,beauty,expression,faceshape,gender,glasses,landmark,race,qualities");
        JSONObject res = client.detect(imagePath, options);
        return res;
    }

    /**
     * @see
     * @param image
     * @return
     * @throws Exception
     */
    public static JSONObject FaceDetect(byte[] image) throws Exception{
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("face_fields","age,beauty,expression,faceshape,gender,glasses,landmark,race,qualities");
        JSONObject res = client.detect(image, options);
        return res;
    }


    /**
     * 人脸对比
     * @return
     * @param imagePath,imagePathTwo
     * @throws Exception
     */
    public static JSONObject FaceMatch(String imagePath,String imagePathTwo) throws Exception{
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("ext_fields", "qualities");
        options.put("image_liveness", "faceliveness,faceliveness");
        options.put("types", "7,13");
        ArrayList<String> path = new ArrayList<String>();
        path.add(imagePath);
        path.add(imagePathTwo);
        JSONObject res = client.match(path, options);
        return res;
    }

    /**
     * 人脸对比
     * @return
     * @param image,imagePathTwo
     * @throws Exception
     */
    public static JSONObject FaceMatch(byte[][] image) throws Exception{
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("ext_fields", "qualities");
        options.put("image_liveness", "faceliveness,faceliveness");
        options.put("types", "7,13");
        JSONObject res = client.match(image, options);
        return res;
    }

}
